package com.le.edu.ws;

import com.le.edu.utils.JwtUtils;
import com.le.edu.utils.WebSocketRemoteContainerUtil;
import jakarta.annotation.Resource;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author Le
 * @create 2024-04-28 23:31
 */
@Component
@Slf4j
@ServerEndpoint("/ai-ws/{token}")
public class AIWebsocketServer {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        try {
            WebSocketRemoteContainerUtil.addSession(JwtUtils.getJSONObject(token), session);
        } catch (Exception e) {
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("token") String token) {
        try {
            WebSocketRemoteContainerUtil.removeSession(JwtUtils.getJSONObject(token));
        } catch (Exception e) {
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message) {
//        log.info("websocket消息: 收到客户端消息:" + message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
}

